<template>
  <div class="signature-container">
    <canvas
      ref="canvasRef"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="endDrawing"
      @mouseleave="endDrawing"
    ></canvas>
    <div class="controls">
      <button @click="clear">清除签名</button>
      <button @click="save">保存签名</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import SignaturePadLib from 'signature_pad'

const emit = defineEmits(['save'])

const canvasRef = ref(null)
let signaturePad = null
let isDrawing = false

onMounted(() => {
  signaturePad = new SignaturePadLib(canvasRef.value, {
    minWidth: 1,
    maxWidth: 3,
    penColor: '#000'
  })
})

const startDrawing = (e) => {
  if (!signaturePad) return
  isDrawing = true
  const { offsetX, offsetY } = e
  signaturePad._strokeBegin({ x: offsetX, y: offsetY }) // 使用私有方法来触发开始绘制
}

const draw = (e) => {
  if (!isDrawing || !signaturePad) return
  const { offsetX, offsetY } = e
  signaturePad._strokeMoveUpdate({ x: offsetX, y: offsetY }) // 使用私有方法来更新绘制
}

const endDrawing = () => {
  if (!signaturePad) return
  isDrawing = false
  signaturePad._strokeEnd() // 使用私有方法来结束绘制
}

const clear = () => {
  signaturePad.clear()
}

const save = () => {
  if (signaturePad.isEmpty()) {
    alert('请先签署')
    return
  }
  const dataURL = signaturePad.toDataURL()
  emit('save', dataURL)
}
</script>

<style scoped>
.signature-container {
  border: 1px solid #ddd;
  padding: 10px;
}

canvas {
  width: 100%;
  height: 200px;
  background: #f8f9fa;
  border: 1px solid #eee;
}

.controls {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #2980b9;
}
</style>
